//
//  MyStreetViewController.m
//  homeland
//
//  Created by SunShine on 13-10-22.
//  Copyright (c) 2013年 xzysun. All rights reserved.
//

#import "MyStreetViewController.h"
#import "StreetInfoService.h"
#import "IconButton.h"
#import "StreetDetailInfoViewController.h"

#define ICON_MARGINS 10.0
#define ICON_SPACES 15.0
#define ICON_WIDTH 90.0
#define ICON_HEIGHT 120.0

@interface MyStreetViewController ()
@property (strong, nonatomic) StreetInfoService *dataService;
@property (strong, nonatomic) NSString *phoneToCall;
@end

@implementation MyStreetViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = [StreetInfoService getService].selectedStreetName;
    [self drawIcons];
    self.navigationItem.rightBarButtonItem = rightNavButton( self, @selector(rightNavButtonAction:),@"街道简介");
    self.dataService = [StreetInfoService getService];
    _dataService.delegate = self;
    [self startLoadingView];
    [_dataService getStreetDetailInfo:_dataService.selectedStreetId];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
-(void) drawIcons
{
    NSArray *iconConfigs = [_config objectForKey:@"items"];
    for (int i = 0; i < [iconConfigs count]; i ++) {
        NSDictionary *iconConfig = [iconConfigs objectAtIndex:i];
        CGFloat iconX = ICON_MARGINS + i%3*(ICON_WIDTH+ICON_SPACES);
        CGFloat iconY = ICON_MARGINS + i/3*(ICON_HEIGHT+ICON_SPACES);
        CGRect iconRect = CGRectMake(iconX, iconY, ICON_WIDTH, ICON_HEIGHT);
        IconButton *button = [[[NSBundle mainBundle]loadNibNamed:@"IconButton" owner:self options:nil] objectAtIndex:0];
        button.frame = iconRect;
        NSString *imageName = [iconConfig objectForKey:@"image"];
        button.iconImageView.image = [UIImage imageNamed:imageName];
        NSString *buttonTitle = [iconConfig objectForKey:@"name"];
        button.iconTitleLabel.text = buttonTitle;
        button.targetStr = [iconConfig objectForKey:@"target"];
        button.userInteractionEnabled = YES;
        //初始化触摸事件
        [button addTarget:self action:@selector(tapIconEvent:) forControlEvents:UIControlEventTouchUpInside];
        [button addTarget:self action:@selector(iconTouchedDown:) forControlEvents:UIControlEventTouchDown];
        [button addTarget:self action:@selector(iconTouchCancel:) forControlEvents:UIControlEventTouchCancel];
        [button addTarget:self action:@selector(iconTouchCancel:) forControlEvents:UIControlEventTouchDragExit];
        [self.scrollView addSubview:button];
    }
    //控制scroll content的高度
    int numOfLines = ceil([iconConfigs count]/3.0);
    CGFloat totalHeight = ICON_MARGINS*2+numOfLines*ICON_HEIGHT+(numOfLines-1)*ICON_SPACES;
    self.scrollView.contentSize = CGSizeMake(320.0, totalHeight);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Button Actions
- (IBAction)phoneButtonAction:(id)sender
{
    NSString* phone = _dataService.streetDetailInfo.phone;
    if ([phone rangeOfString:@","].location != NSNotFound) {
        NSLog(@"准备截断电话号码%@",phone);
        phone = [phone substringToIndex:[phone rangeOfString:@","].location];
    }
    NSLog(@"点击了电话按钮%@",phone);
    self.phoneToCall = phone;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString  stringWithFormat:@"您是否需要拨打电话%@",phone] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = PHONE_ALERT_TAG;
    [alert show];
}

-(IBAction)mapButtonAction:(id)sender
{
    //暂不提供点击
}

-(void)rightNavButtonAction:(id)sender
{
    StreetDetailInfoViewController *detailVC = [[StreetDetailInfoViewController alloc] initWithNibName:@"StreetDetailInfoViewController" bundle:nil];
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - Alert View Delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == PHONE_ALERT_TAG) {
        if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",_phoneToCall]]];
        }
    }
}

#pragma mark - Icon Actions
//icon的点击事件
-(void)tapIconEvent:(id)sender
{
    IconButton *icon = (IconButton *)sender;
    NSLog(@"click icon:%@",icon.iconTitleLabel.text);
    icon.backgroundColor = [UIColor whiteColor];
    //进入下一级页面
    Class tempClass =  NSClassFromString(icon.targetStr);
    if (!tempClass) {
        NSLog(@"target%@类型不正确",icon.targetStr);
        return;
    }
    ConfigableViewController *vc = [[tempClass alloc]initWithNibName:icon.targetStr bundle:nil];
    NSDictionary *vcConfig = [NSDictionary dictionaryWithObjectsAndKeys:icon.iconTitleLabel.text,@"key",nil];
    
    vc.config = vcConfig;
    [self.navigationController pushViewController:vc animated:YES];
}

//icon的按下事件，这里主要是变个颜色
-(void)iconTouchedDown:(id) sender
{
    IconButton *icon = (IconButton *)sender;
    icon.backgroundColor = [UIColor colorWithRed:0.50 green:0.68 blue:0.84 alpha:1.0];
    NSLog(@"icon %@ touch down",icon.iconTitleLabel.text);
}

//icon的取消事件，包含拖拽出控件，这里主要是变回颜色
-(void)iconTouchCancel:(id)sender
{
    IconButton *icon = (IconButton *)sender;
    icon.backgroundColor = [UIColor whiteColor];
    NSLog(@"icon %@ touch cancel",icon.iconTitleLabel.text);
}

#pragma mark - Data Service Delegate
-(void)loadDataFinished
{
    [self stopLoadingView];
    [_phoneButton setTitle:_dataService.streetDetailInfo.phone forState:UIControlStateNormal];
    [_mapButton setTitle:_dataService.streetDetailInfo.address forState:UIControlStateNormal];
}

-(void)loadDataFaild:(NSString *)msg
{
    [self stopLoadingView];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    //显示空白
    [_phoneButton setTitle:@"" forState:UIControlStateNormal];
    [_mapButton setTitle:@"" forState:UIControlStateNormal];
}

@end
